package com.liyghting.datastructurealgorithm.queue;

/**
 * 循环队列
 * 
 * @author LiYiGuang
 * @date 2018/11/22 16:26
 */
public class CycleQueue {
	private String[] items;
	private int head;
	private int tail;

	public CycleQueue(int n) {
		items = new String[n];
	}

	// 入队
	public boolean enqueue(String item) {
		// 队满
		if ((tail + 1) % items.length == head)
			return false;
		items[tail] = item;
		tail = (tail + 1) % items.length;
		return true;
	}

	// 出队
	public String dequeue() {
		// 如果 head == tail 表示队列为空
		if (head == tail)
			return null;
		String item = items[head];
		head = (head + 1) % items.length;
		return item;
	}

	public void printAll() {
		if (head == tail)
			return;
		for (int i = head; i % items.length != tail; i++) {
			System.out.print(items[i] + " ");
		}
		System.out.println();
	}

	public static void main(String[] args) {
		CycleQueue queue = new CycleQueue(10);
		for (int i = 0; i < 10; i++) {
			queue.enqueue(i + "");
		}
		queue.printAll();
		System.out.println(queue.head + "--" + queue.tail);
		for (int i = 0; i < 3; i++) {
			queue.dequeue();
		}
		queue.printAll();
		System.out.println(queue.head + "--" + queue.tail);
	}
}
